//
//  NSMNavSearchBar.m
//  iShow
//
//  Created by nsm on 2018/7/26.
//  Copyright © 2018年 nani. All rights reserved.
//

#import "NSMNavSearchBar.h"

@interface NSMNavSearchBar ()
@property (nonatomic, strong) UITextField *textField;
@end

@implementation NSMNavSearchBar

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.tintColor = THEME_COLOR;
        self.placeholder = @"搜索";
        self.clipsToBounds = YES;
        // 关闭自动大写
        self.autocapitalizationType = UITextAutocapitalizationTypeNone;
        // 文本输入框设置
        self.textField.font = CustomFont(14);
        self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchFieldCornerRadius = -1;
    }
    return self;
}

- (void)setContentInset:(UIEdgeInsets)contentInset {
    _contentInset = contentInset;
    
    [self layoutIfNeeded];
}

- (void)setSearchFieldCornerRadius:(CGFloat)searchFieldCornerRadius {
    _searchFieldCornerRadius = searchFieldCornerRadius;
    
    [self layoutIfNeeded];
}

- (UITextField *)textField {
    if (!_textField) {
        if (@available(iOS 13, *)) {
            _textField = self.searchTextField;
        } else {
            _textField = [self valueForKey:@"_searchField"];
        }
        _textField.borderStyle = UITextBorderStyleNone;
    }
    return _textField;
}

- (void)layoutSubviews {
    // [super layoutSubviews];
    
    // 修改UITextField,宽度会在取消按钮显示的时候自动变化(self.showsCancelButton打开使用)
    // CGFloat width = self.textField.width + UIEdgeInsetsGetWidth(self.contentInset);
    self.textField.frame = CGRectMake(self.contentInset.top,
                                      self.contentInset.left,
                                      self.width - UIEdgeInsetsGetWidth(self.contentInset),
                                      self.height - UIEdgeInsetsGetHeight(self.contentInset));
    // 有可能改变了contentInset导致高度变化,所以圆角设置放到这里更合理
    self.textField.layer.masksToBounds = YES;
    if (self.searchFieldCornerRadius < 0)
        self.textField.layer.cornerRadius = self.textField.height/2;
    else
        self.textField.layer.cornerRadius = self.searchFieldCornerRadius;
}

@end
